var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var isRefresh = false;
var img_refresh = false;
var _limitMenu = system.MENULIMIT.BASE23;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'base/product/list';
var pdata = {};
var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"base/product/to_add";
			data = {oper:oper,callback:this.callback};
		}else if(oper == 'edit'){
			url = config.BASEPATH+"base/product/to_update?pd_id="+id;
			data = {oper:oper,callback:this.callback};
		}else{
			return false;
		}
		$.dialog({
		   	id:id,
		   	title:false,
		   	data: data,
		   	max: false,
		   	min: false,
		   	fixed:false,
		   	drag:false,
		   	resize:false,
		   	lock:false,
		   	content:'url:'+url,
		   	close:function(){
		   		if(isRefresh){
		   			THISPAGE.reloadData();
		   			isRefresh=false;
			   	}
		   	}
	    }).max();
	},
	imports:function(){
		$.dialog({
			title : '商品资料批量导入',
			content : 'url:'+config.BASEPATH+"base/product/to_import_product",
			data: {callback: this.callback},
			width : 550,
			height : 350,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	},
	del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
			var pd_code = rowData.pd_code;
			$.ajax({
				type:"POST",
				url:config.BASEPATH +"base/product/checkOptionChange",
				data:"optionType=product&pd_code="+pd_code,
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						if(data.data == "sucess"){
							$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
								$.ajax({
									type:"POST",
									url:config.BASEPATH+'base/product/del',
									data:{"pd_id":rowId,"pd_code":pd_code},
									cache:false,
									dataType:"json",
									success:function(data){
										if(undefined != data && data.stat == 200){
											Public.tips({type: 3, content : '删除成功!'});
											$('#grid').jqGrid('delRowData', rowId);
										}else{
											Public.tips({type: 1, content : '删除失败!'});
										}
									}
								});
							});
						}else{
							Public.tips({type: 2, content : "商品存在业务关联，不能删除！"});
						}
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		}else{
			Public.tips({type: 1, content : '请选择数据!'});
		}	
    },
    addBarCode: function(id){//条形码录入
    	$.dialog({
		   	id:id,
		   	title:'条形码录入',
			max: false,
			min: false,
			width:800,
			height:530,
			fixed:true,
			drag: true,
		   	resize:false,
		   	lock:false,
		   	content:'url:'+config.BASEPATH+'base/product/to_barcode_add?pd_id='+id
	    });
    },
    addImage: function(obj,id){//新增图片
    	var rowData = $("#grid").jqGrid("getRowData", id);
		var pd_code = rowData.pd_code;
		if(pd_code != undefined && pd_code != ''){
			$.dialog({ 
				id: 'id',
				title: '商品图片',
				max: false,
				min: false,
				width: '830px',
				height: '400px',
				fixed:false,
				drag: true,
				content:'url:'+config.BASEPATH+'base/product/to_img_add?pd_code='+pd_code,
				close:function(){
			   		if(img_refresh){
			   			$(obj).css("color","green");
			   			img_refresh=false;
				   	}
			   	}
			});
		}else{
			Public.tips({type: 1, content : '数据出错，请联系管理员!!!'});
		}
    },
    shopPrice: function(id){//分店价格
    	var rowData = $("#grid").jqGrid("getRowData", id);
		var pd_code = rowData.pd_code;
		if(pd_code != undefined && pd_code != ''){
			$.dialog({ 
				id: 'id',
				title: '分店价格',
				max: false,
				min: false,
				width: '830px',
				height: '400px',
				fixed:false,
				drag: true,
				content:'url:'+config.BASEPATH+'base/product/to_shop_price_list?pd_code='+pd_code
			});
		}else{
			Public.tips({type: 1, content : '数据出错，请联系管理员!!!'});
		}
    },
    callback: function(data, oper, dialogWin){
		var gridData = $("#grid").data('gridData');
		if(!gridData){
			gridData = {};
			$("#grid").data('gridData', gridData);
		}
		gridData[data.id] = data;
		if(oper == "edit") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		} 
		if(oper == "add"){
			$("#grid").jqGrid('addRowData', data.id, data, 'first');
		}
	},
	operFmatter:function(val, opt, row) {
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i> <i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-barcode" title="条码">&#xe62b;</i>';
		if(row.pdm_id != '' && row.pdm_id != null){
			html_con += '<i class="iconfont i-hand ui-icon-image" style="color:green;" title="图片上传">&#xe654;</i>';
		}else{
			html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		}
		html_con += '<i class="iconfont i-hand ui-icon-price" title="分店价格">&#xe610;</i>';
		html_con += '</div>';
		return html_con;
	},
	initYear:function(){
		var tim = new Date();
		var currentYear = tim.getFullYear();
		yearInfo = {
			data:{items:[
			        {year_Code:"",year_Name:"全部"},
					{year_Code:""+parseInt(currentYear+1)+"",year_Name:""+parseInt(currentYear+1)+""},
					{year_Code:""+parseInt(currentYear)+"",year_Name:""+parseInt(currentYear)+""},
					{year_Code:""+parseInt(currentYear-1)+"",year_Name:""+parseInt(currentYear-1)+""},
					{year_Code:""+parseInt(currentYear-2)+"",year_Name:""+parseInt(currentYear-2)+""},
					{year_Code:""+parseInt(currentYear-3)+"",year_Name:""+parseInt(currentYear-3)+""},
					{year_Code:""+parseInt(currentYear-4)+"",year_Name:""+parseInt(currentYear-4)+""},
					{year_Code:""+parseInt(currentYear-5)+"",year_Name:""+parseInt(currentYear-5)+""},
					{year_Code:""+parseInt(currentYear-6)+"",year_Name:""+parseInt(currentYear-6)+""},
					{year_Code:""+parseInt(currentYear-7)+"",year_Name:""+parseInt(currentYear-7)+""}
				]}
		}
		yearCombo = $('#span_year').combo({
			data:yearInfo.data.items,
			value: 'year_Code',
			text: 'year_Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: true,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.year_Code);
				}
			}
		}).getCombo();
	  },
	  initDict:function(){
		  seasonCombo = $('#span_pd_season_Code').combo({
				value: 'dtl_code',
				text: 'dtl_name',
				width :206,
				height: 80,
				listId:'',
				defaultSelected: 0,
				editable: true,
				callback:{
					onChange: function(data){
						if(data.dtl_name == "全部"){
							$("#pd_season").val("");
						}else{
							$("#pd_season").val(data.dtl_name);
						}
					}
				}
			}).getCombo(); 
			$.ajax({
				type:"POST",
				url:config.BASEPATH +"base/dict/listByProduct",
				data:"",
				cache:false,
				dataType:"json",
				success:function(data){
					seasonInfo = data.data.seasonitemsquery;
					seasonCombo.loadData(seasonInfo);
				}
			});
		},
		doQueryBrand : function(){
			commonDia = $.dialog({
				title : '选择品牌',
				content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
				data : {multiselect:false},
				width : 320,
				height : 370,
				max : false,
				min : false,
				cache : false,
				lock: true,
				ok:function(){
					var selected = commonDia.content.doSelect();
					if (!selected) {
						return false;
					}
				},
				close:function(){
					var selected = commonDia.content.doSelect();
					if(selected){
						$("#pd_bd_code").val(selected.bd_code);
						$("#pd_bd_name").val(selected.bd_name);
					}
				},
				cancel:true
			});
		},
		doQuerySupply : function(){
			commonDia = $.dialog({
				title : '选择供货单位',
				content : 'url:'+config.BASEPATH+'buy/supply/to_list_dialog',
				data : {multiselect:false},
				width : 400,
				height : 370,
				max : false,
				min : false,
				cache : false,
				lock: true,
				ok:function(){
					var selected = commonDia.content.doSelect();
					if (!selected) {
						return false;
					}
				},
				close:function(){
					var selected = commonDia.content.doSelect();
					if(selected){
						$("#pd_sp_code").val(selected.sp_code);
						$("#pd_sp_name").val(selected.sp_name);
					}
				},
				cancel:true
			});
		},
		doQueryType : function(){
			commonDia = $.dialog({
				title : '选择商品类别',
				content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
				data : {multiselect:true},
				width : 280,
			   	height : 320,
				max : false,
				min : false,
				cache : false,
				lock: true,
				ok:function(){
					var selected = commonDia.content.doSelect();
					if (!selected) {
						return false;
					}
				},
				close:function(){
					var selected = commonDia.content.doSelect();
					if(selected){
						var pd_tp_code = [];
						var pd_tp_name = [];
						var pd_tp_upcode = [];
						for(var i=0;i<selected.length;i++){
							pd_tp_code.push(selected[i].tp_code);
							pd_tp_name.push(selected[i].tp_name);
							pd_tp_upcode.push(selected[i].tp_upcode);
						}
						$("#pd_tp_code").val(pd_tp_code.join(","));
						$("#pd_tp_name").val(pd_tp_name.join(","));
						$("#pd_tp_upcode").val(pd_tp_upcode.join(","));
					}
				},
				cancel:true
			});
		}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		handle.initYear();
		handle.initDict();
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
		    {name: 'operate', label:'操作',width: 110, fixed:true, formatter: handle.operFmatter, title: false,sortable:false},
		    {name: 'pd_code', label:'商品编号',index: 'pd_code', hidden:true},
			{name: 'pd_no', label:'商品货号',index: 'pd_no', width: 100, title: true,fixed:true,sortable:true},
			{name: 'pd_name',label:'商品名称', index: 'pd_name', width: 160, title: true,sortable:true},
			{name: 'pd_number', label:'厂家款号',index: 'pd_number', width: 100, title: true,fixed:true,sortable:true},
			{name: 'pd_bd_name',label:'品牌', index: 'pd_bd_name', width: 80, title: true,sortable:true},
			{name: 'pd_tp_name',label:'类型', index: 'pd_tp_name', width: 80, title: true,sortable:true},
			{name: 'pd_szg_name',label:'尺码组', index: 'pd_szg_name', width: 80, title: true,sortable:true},
			{name: 'pd_cost_price',label:'成本价', index: 'pd_cost_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatByCost},
			{name: 'pd_batch_price',label:'批发价', index: 'pd_batch_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatByBatch},
			{name: 'pd_buy_price',label:'进货价', index: 'pd_buy_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatByEnter},
			{name: 'pd_sort_price',label:'配送价', index: 'pd_sort_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatByDistribute},
			{name: 'pd_vip_price',label:'会员价', index: 'pd_vip_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatByVip},
			{name: 'pd_sell_price',label:'零售价', index: 'pd_sell_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatBySell},
			{name: 'pd_sign_price',label:'标牌价', index: 'pd_sign_price',align:'right', width: 50, title: false,sortable:true,formatter: PriceLimit.formatBySell},
			{name: 'pd_style',label:'款式', index: 'pd_style', width: 40,align:'center', title: false,sortable:true},
			{name: 'pd_unit',label:'单位', index: 'pd_unit', width: 40,align:'center', title: false,sortable:true},
			{name: 'pd_season',label:'季节', index: 'pd_season', width: 40,align:'center', title: false,sortable:true},
			{name: 'pd_year',label:'年份', index: 'pd_year', width: 40, title: false,align:'center',sortable:true},
			{name: 'pd_date',label:'上市时间', index: 'pd_date', width: 80, title: false,align:'center',sortable:true},
			{name: 'pd_fabric',label:'面料', index: 'pd_fabric', width: 60, title: false,align:'center',sortable:true},
			{name: 'pd_add_manager',label:'创建人', index: 'pd_add_manager', width: 80, title: false,sortable:true},
			{name: 'pd_add_date',label:'创建日期', index: 'pd_add_date', width: 80, title: false,align:'center',sortable:true},
			{name: 'pd_mod_manager',label:'修改人', index: 'pd_mod_manager', width: 80, title: false,sortable:true},
			{name: 'pd_mod_date',label:'修改日期', index: 'pd_mod_date', width: 80, title: false,align:'center',sortable:true}
//			{name: 'pdm_buy_cycle',label:'进货周期', index: 'pdm_buy_cycle', width: 60, title: false,align:'center',sortable:true},
//			{name: 'pd_sell_cycle',label:'零售周期', index: 'pd_sell_cycle', width: 60, title: false,align:'center',sortable:true},
//			{name: 'pdm_sp_name',label:'供货商', index: 'pdm_sp_name', width: 120, title: true,sortable:true}
	    ];
		$('#grid').jqGrid({
			url:queryurl,			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:30,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'pd_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'searchContent='+$("#SearchContent").val();
		params += '&pd_no='+$("#pd_no").val();
		params += '&pd_name='+Public.encodeURI($("#pd_name").val());
		params += '&pd_spell='+Public.encodeURI($("#pd_spell").val());
		params += '&pd_year='+$("#pd_year").val();
		params += '&pd_season='+Public.encodeURI($("#pd_season").val());
		params += '&pd_tp_code='+$("#pd_tp_code").val();
		params += '&pd_tp_upcode='+$("#pd_tp_upcode").val();
		params += '&pd_bd_code='+$("#pd_bd_code").val();
		params += '&pd_sp_code='+$("#pd_sp_code").val();
		params += '&pd_number='+$("#pd_number").val();
		return params;
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		$('#SearchContent').on('keyup',function(event){
			if (event.keyCode==13){
				$('#btn-search').click();
			}
		});
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		//重置
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			$("#SearchContent").val('');
			$("#pd_no").val('');
			$("#pd_name").val('');
			$("#pd_spell").val('');
			$("#pd_year").val('');
			yearCombo.loadData(yearInfo.data.items,[0]);
			$("#pd_season").val('');
			seasonCombo.loadData(seasonInfo,[0]);
			$("#pd_tp_name").val('');
			$("#pd_tp_code").val('');
			$("#pd_tp_upcode").val('');
			$("#pd_bd_name").val('');
			$("#pd_bd_code").val('');
			$("#pd_sp_name").val('');
			$("#pd_sp_code").val('');
			$("#pd_number").val('');
		});
		//修改
		$('#grid').on('click', '.operating .ui-icon-pencil', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.operate('edit', id);
		});
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.del(id);
		});
		//条码
		$('#grid').on('click', '.operating .ui-icon-barcode', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.PRINT)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.addBarCode(id);
		});
		//图片
		$('#grid').on('click', '.operating .ui-icon-image', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.addImage(this,id);
		});
		//分店价格
		$('#grid').on('click', '.operating .ui-icon-price', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.shopPrice(id);
		});
		//导入
		$('#btn-import').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.IMPORT)) {
				return ;
			};
			handle.imports();
		});
		//导出
		$('#btn-export').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.EXPORT)) {
				return ;
			};
			window.open(config.BASEPATH+'base/product/listReport?' + THISPAGE.buildParams());
		});
	}
}
THISPAGE.init();